<template>
	<view>
		<view class="chat">
			<!-- <view style="background-color: #F6F6F6; text-align: center; font-size: 28rpx; color: green;" @click="more">
				查看历史记录</view> -->
			<scroll-view :style="{height: `${windowHeight}rpx`}" id="scrollview" scroll-y="true" :scroll-top="scrollTop"
				:scroll-with-animation="true" class="scroll-view">
				<!-- 聊天主体 -->
				<view id="msglistview" class="chat-body">
					<!-- 聊天记录 -->
					<view v-for="(item,index) in msgList" :key="index">
						<!-- 自己发的消息 -->
						<view class="item self" v-if="item.content != '' && item.is_img == 0">
							<!-- 文字内容 -->
							<view class="content right">
								<mp-html :content="item.content" />
							</view>
							<!-- 头像 -->
							<view class="avatar">
								<image :src="userInfo.avatar"></image>
							</view>
						</view>
						<view class="item1 self1" v-if="item.content != '' && item.is_img == 1">
							<!-- 文字内容 -->
							<view class="content2 right1" @tap="previewImage(item.content)">
								<image :src="item.content"></image>
							</view>
							<!-- 头像 -->
							<view class="avatar1">
								<image :src="userInfo.avatar"></image>
							</view>
						</view>
						<!-- 别人发的消息 -->
						<view class="item Ai" v-if="item.botContent != '' && item.is_img == 0">
							<!-- 头像 -->
							<view class="avatar">
								<image :src="avatar">
								</image>
							</view>
							<!-- 文字内容 -->
							<view class="content left">
								<mp-html :content="item.botContent" />
							</view>
						</view>
						<view class="item1 Ai" v-if="item.botContent != '' && item.is_img == 1">
							<!-- 头像 -->
							<view class="avatar1">
								<image :src="avatar">
								</image>
							</view>
							<!-- 文字内容 -->
							<view class="content1 left1" @tap="previewImage(item.content)">
								<image :src="item.botContent"></image>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<!-- 底部消息发送栏 -->
			<!-- 用来占位，防止聊天消息被发送框遮挡 -->
			<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
				<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
					<view class="uni-textarea" :style="{ 'padding-bottom': isUploading ? '300rpx' : '60rpx' }">
						<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
							:show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus"
							@blur="blur" auto-height></textarea>
					</view>
					<view class="upload" :style="{ 'margin-bottom': isUploading ? '300rpx' : '60rpx' }" @click="upload">
						<u-icon name="plus-circle" color="black" size="30"></u-icon>
					</view>
					<button :style="{ 'margin-bottom': isUploading ? '300rpx' : '60rpx' }" @click="handleSend"
						class="send-btn">发送</button>
					<view v-if="isUploading" class="isUploading">
						<view>
							<view class="addbox1_son2">
								<view class="pic-box">
									<view class="pic-box-son" v-for="(picitem,picindex) in picArr" :key="picindex">
										<!-- 删除按钮 -->
										<view class="delbtn" @tap="delpic(picindex)"></view>
										<image :src="picitem"></image>
									</view>
									<view v-show="picArr.length<5" class="pic-box-son" @tap="sendImg">
										<view>点击<br>发送图片</view>
										<view>（最多5张）</view>
									</view>
									<view v-if="flag == 1" class="pic-box-son" @click="gotoAdvertisement">
										<view>点击<br>接入广告</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		data
	} from '../../uni_modules/uview-ui/libs/mixin/mixin'
	export default {
		data() {
			return {
				picArr: [],
				isInputting: true,
				isUploading: false,
				receiverId: '',
				markdown: '',
				html: '',
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: '',
				//发送的消息
				chatMsg: "",
				userInfo: {},
				msgList: [],
				avatar: '',
				picture: [],
				imgUrl: '',
				flag:0,
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight
			}
		},
		onPullDownRefresh() {
			let that = this;
			that.more();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000)
		},
		onUnload() {
			uni.closeSocket();
			uni.offKeyboardHeightChange()
		},
		onLoad(query) {
			if(query.flag){
				this.flag = query.flag
			}
			this.userId = uni.getStorageSync("userId")
			// 设置页面标题为聊天对象的昵称
			uni.setNavigationBarTitle({
				title: query.nickname
			});
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height - 30)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})
			this.receiverId = query.receiverId;
			this.connect();
			this.getLoginUser();
			this.getMyMessage();
		},
		methods: {
			gotoAdvertisement(){
				uni.navigateTo({
					url:'/pages/add_advertisement/add_advertisement'
				})
			},
			previewImage(url) {
			      // 在这个方法中触发图片预览功能
			      uni.previewImage({
			        current: url, // 当前显示图片的链接
			        urls: [url] // 需要预览的图片链接列表
			      });
			    },
			// 上传图片
			sendImg: function() {
				let that = this;
				let num = 5 - this.picArr.length;
				let count = num; // 自定义一次性最多可选几张
				uni.chooseImage({
					count: count, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						const filePaths = res.tempFilePaths;
						let selected = this.picArr
						for (let i = 0; i < filePaths.length; i++) {
							that.picture[i] = "http://s1qq2mel1.hn-bkt.clouddn.com/images/" + that.userId +
								"/chatInfo/" + filePaths[i];
							that.$ajax(that.$url.upLoad, "GET", null, function(resp) {
								let token = resp.data.result;
								let now = new Date();
								that.imgUrl = 'images/' + that.userId + "/chatInfo/" +
									filePaths[i]; // 图片链接，其中的 / 会自动生成一个名为images的文件夹， // 则是两个
								let self = this
								wx.uploadFile({
									filePath: filePaths[i], // ctx.takePhoto拍照获取的图片链接
									url: "https://upload-z2.qiniup.com", // 七牛云地址
									name: "file",
									formData: {
										token,
										key: that.imgUrl,
										insertOnly: 0,
									},
									success: (a) => {
										let res = a.data
										res = JSON.parse(res)
										if (res.code == '1') {
											const {
												data
											} = res
											self.avatar = data.url
											self.cdnUrl = getApp().globalData.cdnUrl +
												data.url
										}

										wx.hideLoading()
										wx.showToast({
											title: '发送成功',
											icon: 'none',
											duration: 2000
										})
										let obj = {
											botContent: "",
											receiverId: that.receiverId,
											titleId: 0,
											content: that.picture[i],
											is_img: 1,
										}
										that.msgList.push(obj);
										that.imgUrl = '';
										that.webSocket.send({
											data: JSON.stringify(obj)
										});
										that.$ajax(that.$url.chat, "POST", obj,
											function(resp) {

											})
									},
									fail: (res) => {
										return 0;
									},
								})

							})

							this.picArr.unshift(filePaths[i])
						}
						that.picArr = [];
						that.isUploading = false;
					}
				});

			},
			// 删除当前图片
			delpic: function(index) {
				this.picArr.splice(index, 1)
			},
			upload() {
				let that = this;
				that.isUploading = !that.isUploading;
			},
			getMyMessage() {
				let that = this;
				that.$ajax(that.$url.searchMyInfo + "?senderId=" + this.receiverId, "GET", null, function(resp) {
					that.msgList = resp.data.result;
				})
			},
			getLoginUser() {
				let that = this;
				that.$ajax(that.$url.getLoginUser, "GET", null, function(resp) {
					that.userInfo = resp.data.result;
				})
				//获取私信对象的昵称、头像
				that.$ajax(that.$url.getUser + "?userId=" + that.receiverId, "GET", null, function(resp) {
					that.avatar = resp.data.result.avatar
				})
			},
			more() {
				let that = this;
				this.searchHistoryInfo();
			},
			searchHistoryInfo() {
				let that = this;
				let data = {
					receiverId: '',
					senderId: ''
				}
				// that.$ajax(that.$url.searchInfoHistory, "POST", data, function(resp) {
				// 	let result = resp.data.result;
				// 	that.msgList = result;
				// })
			},
			connect() {
				this.userName = uni.getStorageSync('userName');
				console.log(this.userName);
				// 创建连接
				let to = uni.getStorageSync('to');
				let from = uni.getStorageSync('userId');
				let to_name = uni.getStorageSync('to_name');
				let that = this;
				let ws = uni.connectSocket({
					url: 'wss://a5942g1060.zicp.fun/api/websocket/' + from,
					success() {
						console.log('WebSocket连接成功');
					},
					fail() {
						console.log('WebSocket连接失败');
					}
				});
				this.webSocket = ws;
				// 监听连接事件
				ws.onOpen(() => {
					console.log('WebSocket已连接');

					// 在连接成功后发送数据
					// const sendData = {
					// 	from: from, // 必须包含属性from
					// 	from_name: this.userName, // 必须包含属性from
					// 	content: this.content, // 必须包含属性content
					// 	to: to, // 必须包含属性to
					// 	to_name: to_name, // 必须包含属性to
					// 	sendToAll: false // 必须包含属性sendToAll
					// 	// 其他数据...
					// };
					// ws.send({
					// 	data: JSON.stringify(sendData)
					// });
				});

				// 监听服务器推送消息事件
				wx.onSocketMessage(data => {
					console.log('收到消息', data.data);
					let obj = {
						botContent: data.data,
						recordId: 0,
						titleId: 0,
						content: '',
						userId: 0
					};
					that.msgList.push(obj);
					this.msg = 'data';
				});

				// 监听错误事件
				ws.onError(error => {
					console.log('WebSocket错误', error);
				});

				// 监听关闭事件
				ws.onClose(() => {
					console.log('WebSocket已关闭');
				});

				// 发送消息
				ws.send({
					data: 'Hello WebSocket',
					success() {
						console.log('消息发送成功');
					}
				});
			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			// 发送消息
			handleSend() {
				let that = this;
				//如果消息不为空
				if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
					let obj = {
						botContent: "",
						receiverId: that.receiverId,
						titleId: 0,
						content: this.chatMsg,
						is_img: 0,
					}
					this.msgList.push(obj);
					this.chatMsg = '';
					that.webSocket.send({
						data: JSON.stringify(obj)
					});
					that.$ajax(that.$url.chat, "POST", obj, function(resp) {

					})
				} else {
					this.$modal.showToast('不能发送空白消息')
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
	.isUploading {
		position: absolute;
	}

	.addbox1_son2 {
		width: 750rpx;
		display: flex;
		flex-wrap: wrap;
		flex-direction: row;
		align-items: center;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid rgba(0, 0, 0, .1);
	}

	.pic-box {
		width: 750rpx;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		/* justify-content: center; */
	}

	.pic-box-son {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-left: 20rpx;
		margin-bottom: 20rpx;
		width: 152rpx;
		height: 152rpx;
		padding: 4rpx;
		border-radius: 6rpx;
		border: 2rpx dashed rgba(0, 0, 0, .2);
	}

	.pic-box-son image {
		width: 100%;
		height: 100%;
		border-radius: 6rpx;
	}

	.pic-box-son>view:first-child {
		font-size: 28rpx;
		color: #565656;
		text-align: center;
	}

	.pic-box-son>view:last-child {
		font-size: 24rpx;
		color: #a7a7a7;
		text-align: center;
	}

	.delbtn {
		width: 100%;
		position: relative;
		text-align: center;
		line-height: 32rpx;
		font-size: 46rpx;
	}

	.delbtn::before {
		position: absolute;
		content: '-';
		background-color: #ff9000;
		color: #fff;
		width: 36rpx;
		height: 36rpx;
		border-radius: 50rpx;
		top: 6rpx;
		right: 6rpx;
		z-index: 99;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						// background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;

						image {
							width: 78rpx;
							height: 78rpx;
							align-self: center;
						}
					}
				}

				.item1 {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right1 {
						// background-color: $chatContentbgc;
					}

					.left1 {
						// background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right1::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left1::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
					.content1 {
						position: relative;
						max-width: 570rpx;
						width: 700rpx;
						height: 250rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
					.content1 image{
						// width: auto;
						width: 200rpx;
						height: 240rpx;
					}
					.content2 {
						position: relative;
						max-width: 570rpx;
						width: 570rpx;
						height: 250rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
					.content2 image{
						// width: auto;
						width: 200rpx;
						height: 240rpx;
						padding-left: 340rpx;
					}
					.avatar1 {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						// background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;
						image {
							width: 78rpx;
							height: 78rpx;
							align-self: center;
						}
					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			
			width: 100%;
			height: 177rpx;
			background: #F4F5F7;

			.send-msg {
				box-shadow: 0px -1px 10px rgba(0, 0, 0, 0.2);
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #F4F5F7;
			}

			.uni-textarea {
				padding-bottom: 60rpx;

				textarea {
					width: 458rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 5rpx 8rpx;
				}
			}

			.upload {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: $sendBtnbgc;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}

	}
</style>